package com.tanhua.gateway.filters;

import com.alibaba.cloud.commons.lang.StringUtils;
import com.alibaba.fastjson.JSON;
import com.tanhua.commons.utils.JwtUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.RequestPath;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Component
public class AuthFilter implements GlobalFilter, Ordered {

    @Value("${gateway.excludedUrls}")
    private List<String> excludeUrls;

    /**
     * 过滤器的业务逻辑
     * exchange：请求上下文--获取request，response
     * chain：过滤器链 -- 请求放行
     */
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        ServerHttpRequest request = exchange.getRequest();
        //1、获取请求连接
        String path = request.getURI().getPath();
        //判断
        if (excludeUrls.contains(path)) {
            //放行
            return chain.filter(exchange);
        }
        //获取token
        String token = request.getHeaders().getFirst("Authorization");
        //针对页面端的token问题
        if (!StringUtils.isEmpty(token)) {
            token = token.replaceAll("Bearer ", "");
        }
        //验证token
        boolean bool = JwtUtils.verifyToken(token);
        if (bool) {
            //放行
            return chain.filter(exchange);
        } else {
            //验证不通过
            ServerHttpResponse response = exchange.getResponse();
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            //return response.setComplete(); //响应结束
            //携带数据
            Map<String, Object> map = new HashMap<>();
            map.put("errCode", 401);
            map.put("errMessage", "用户未登录");
            //指定相应的数据头
            response.getHeaders().add("Content-Type", "application/json;charset=UTF-8");
            //需要将返回的对象数据转化为byte数组
            byte[] data = JSON.toJSONBytes(map);
            //构造DataBuffer对象
            DataBuffer buffer = response.bufferFactory().wrap(data); //数据DatBuffer
            return response.writeWith(Mono.just(buffer));
        }

    }

    @Override
    public int getOrder() {
        return Ordered.LOWEST_PRECEDENCE;  //返回值越小，优先级越高
    }
}
